package qjc.o_动态规划;

public class o9_最长有效括号 {
    public int longestValidParentheses(String s) {
        if (s == null || s.length() < 2) {
            return 0;
        }
        int n = s.length();
        int[] dp = new int[n];
        int max = 0;
        for (int i = 1; i < n; i++) {
            if (s.charAt(i) == ')') {
                if (s.charAt(i - 1) == '(') {
                    dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2;
                } else {
                    int j = i - dp[i - 1] - 1;
                    if (j >= 0 && s.charAt(j) == '(') {
                        dp[i] += dp[i - 1] + 2;
                        if (j >= 1) {
                            dp[i] += dp[j - 1];
                        }
                    }
                }
                max = Math.max(max, dp[i]);
            }
        }
        return max;
    }
}
